﻿using System;
using System.Linq;
using SC2ProArena.Domain.Model.Players;
using SC2ProArena.Domain.Model.Games;

namespace SC2ProArena.Infrastructure.EFPersistence.Players
{
	public class PlayerRepository : IPlayerRepository
	{
		private SC2ProArenaEntities _context;

		public PlayerRepository(SC2ProArenaEntities context)
		{
			_context = context;
		}

		public Domain.Model.Players.Player[] FindBy(FindPlayersQuery query = null)
		{
			if (query == null)
				return ToDomainArray(_context.Players);

			var dataToReturn = _context.Players.AsQueryable();
			if (query.RaceFilter.HasValue)
			{
				var raceFilter = query.RaceFilter.Value.ToString().ToLower();
				dataToReturn = dataToReturn.Where(x => x.Race.Name == raceFilter);
			}

			return ToDomainArray(dataToReturn);
		}

		private Domain.Model.Players.Player[] ToDomainArray(IQueryable<Player> query)
		{
			return query.ToArray().Select(x => new Domain.Model.Players.Player()
			{
				Id = x.Id,
				FirstName = x.FirstName,
				LastName = x.LastName,
				NickName = x.NickName,
				Race = (Domain.Model.Games.Race)Enum.Parse(typeof(Domain.Model.Games.Race), x.Race.Name, true)
			}).ToArray();
		}
	}
}
